<template>
  <view class="login flex flex-col">
    <view class="login-bg" />
    <NavigationBar navigation-title="登录" :go-back="goBack" />
    <view class="login-form-wrap">
      <image class="login-icon" src="https://cbandu.oss-cn-qingdao.aliyuncs.com/yusj/20250516/icon_logo.png" />
      <view class="title">
        欢迎登录与书加
      </view>

      <up-form
        ref="formRef"
        label-position="top"
        :model="formData"
        :label-width="100"
        :rules="rules"
      >
        <up-form-item
          label="手机号"
          prop="userInfo.accountNumber"
          :border-bottom="false"
        >
          <up-input
            v-model="formData.userInfo.accountNumber"
            placeholder="请输入手机号"
            border="bottom"
            clearable
            placeholder-class="placeholder-style"
            placeholder-style="color: #888"
          />
        </up-form-item>

        <up-form-item
          label="验证码"
          prop="userInfo.validCode"
          :border-bottom="false"
        >
          <up-input
            v-model="formData.userInfo.validCode"
            placeholder="请输入验证码"
            border="bottom"
            clearable
            placeholder-class="placeholder-style"
            placeholder-style="color: #888"
          >
            <template #suffix>
              <up-code
                ref="uCodeRef"
                seconds="60"
                change-text="X秒重新获取"
                @change="codeChange"
              />
              <up-button
                type="primary"
                :plain="true"
                :text="tips"
                shape="circle"
                @tap="getCode"
              />
            </template>
          </up-input>
        </up-form-item>
      </up-form>

      <button class="login-btn" :class="(!formData.userInfo.accountNumber || !formData.userInfo.validCode || !checked) && 'btn-disable'" @tap="submit">
        登录
      </button>

      <view class="login-info">
        <view v-if="!checked" class="check-box" @click="checked = !checked" />
        <image v-else class="check-img" src="https://cbandu.oss-cn-qingdao.aliyuncs.com/yusj/20250516/icon_checked.png" @click="checked = !checked" />
        <text class="info-text">
          我已阅读并同意
        </text>
        <text class="info-link" @click="handleShowPopup(1)">
          《隐私协议》
        </text>
        <text class="info-text">
          &
        </text>
        <text class="info-link" @click="handleShowPopup(2)">
          《用户协议》
        </text>
      </view>
    </view>

    <AgreePrivacy v-model:model-value="modelValue" :type="modelType" />
  </view>
</template>

<script setup lang="ts">
import type uCode from 'uview-plus/components/u-code/u-code.vue';
import type uForm from 'uview-plus/components/u-form/u-form.vue';
import { useUserStore } from '@/store';
import type { LoginParams } from '@/api/user/type';
import { Toast } from '@/utils';

const store = useUserStore();

const formData = ref<{ userInfo: LoginParams }>({
  userInfo: {
    loginType: 'customer_user_login_phone',
    accountNumber: '',
    validCode: '',
  },
});

const rules = ref({
  'userInfo.accountNumber':
    { required: true, message: '请输入正确的手机号', pattern: /^1[3-9]\d{9}$/, trigger: ['blur', 'change'] },
  'userInfo.validCode':
    { required: true, message: '请输入验证码', trigger: ['blur', 'change'] },
});

const modelValue = ref<boolean>(false); // 隐私协议弹窗
const modelType = ref<number>(0); // 协议类型
const checked = ref<boolean>(false);

const handleShowPopup = (type: number) => {
  modelType.value = type;
  modelValue.value = true;
};

const tips = ref<string>();
const formRef = ref<InstanceType<typeof uForm>>();

const codeChange = (text: string) => {
  tips.value = text;
};

const uCodeRef = ref<InstanceType<typeof uCode> | null>(null);
const getCode = () => {
  formRef.value.validateField('userInfo.accountNumber').then(() => {
    if (uni.$u.test.mobile(formData.value.userInfo.accountNumber)) {
      if (uCodeRef.value?.canGetCode) {
        // 模拟向后端请求验证码
        uni.showLoading({
          title: '正在获取验证码',
        });
        setTimeout(() => {
          uni.hideLoading();
          // 通知验证码组件内部开始倒计时
          uCodeRef.value?.start();
        }, 1000);
        store.getCode(formData.value.userInfo.accountNumber);
      }
      else {
        uni.$u.toast('倒计时结束后再发送');
      }
    }
  });
};
function submit() {
  if (!checked.value) {
    Toast('请先阅读并同意隐私协议和用户协议');
    return;
  }
  formRef.value.validate().then((valid: any) => {
    if (valid) {
      store.login(formData.value.userInfo).then(() => {
        uni.reLaunch({ url: '/pages/tab/home/index' });
      }).catch(() => {
      });
    }
  }).catch(() => {
  });
}
const goBack = () => {
  uni.reLaunch({ url: '/pages/tab/home/index' });
};

// 分享
uni.showShareMenu({
  withShareTicket: true,
  menus: ['shareAppMessage', 'shareTimeline'],
});
onShareAppMessage(() => {
  return {
    title: store.share_txt,
    imageUrl: store.share_pic_url,
  };
});
</script>

<style lang="scss" scoped>
.login {
  position: relative;
  width: 100%;
  min-height: 100%;
  padding-top: 260rpx;

  .login-bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 750rpx;
    height: 560rpx;
    background: linear-gradient( 180deg, #C3EFA9 0%, rgba(255,255,255,0) 100%);
  }

  .login-form-wrap {
    width: 100%;
    flex: 1;
    padding: 0 62rpx;
    display: flex;
    flex-direction: column;
    align-items: center;

    .login-icon {
      width: 160rpx;
      height: 160rpx;
    }

    .title {
      padding-top: 32rpx;
      padding-bottom: 90rpx;
      font-size: 48rpx;
      color: #1E2121;
      line-height: 72rpx;
    }
  }

  .login-info {
    display: flex;
    align-items: center;
    font-size: 24rpx;
    line-height: 36rpx;
    margin-bottom: 60rpx;

    .check-box {
      width: 32rpx;
      height: 32rpx;
      margin: 16rpx;
      border-radius: 4rpx;
      border: 1rpx solid #251504;
      background: #fff;
    }

    .check-img {
      width: 32rpx;
      height: 32rpx;
      margin: 16rpx;
    }

    .info-text {
      color: #313131;
    }

    .info-link {
      color: #31C966;
    }
  }

  .login-btn {
    width: 100%;
    height: 92rpx;
    margin: 34rpx 0 64rpx;
    border-radius: 46rpx;
    font-size: 32rpx;
    line-height: 92rpx;
    background: linear-gradient( 90deg, #FFA029 0%, #FFCD29 100%);
    color: #fff;
  }

  .btn-disable {
    background: #CFCFCF;
  }
}
:deep(.u-form) {
  width: 100%;
}
:deep(.u-form-item__body) {
  padding: 30rpx 0 !important;
}

:deep(.u-form-item__body__left__content__label) {
  font-size: 32rpx !important;
  line-height: 48rpx;
  color: #251504 !important;
  font-weight: normal;
}
:deep(.u-input__content__field-wrapper__field) {
  font-size: 28rpx !important;
  color: #251504 !important;
}

:deep(.u-input) {
  padding: 12rpx 0 !important;
}

:deep(.u-reset-button) {
  font-size: 28rpx !important;
  line-height: 42rpx !important;
  color: #31C966 !important;
  border: none !important;
  background: transparent !important;
}
</style>
